from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy

#from .view import CommonApi
from wrapcache import MemoryAdapter

from config import config
from sqlalchemy import MetaData



import logging
from logging.config import fileConfig
fileConfig('logging_config.ini')
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
#logger.debug('often makes a very good meal of %s', 'visiting tourists')



###初始化插件
#定义命名惯例
naming_convention = {
    "ix": 'ix_%(column_0_label)s',
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(column_0_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s"
}
db = SQLAlchemy(metadata=MetaData(naming_convention=naming_convention))

#routRgster = CommonApi()


login_manager = LoginManager()





def create_app(config_name):
    app = Flask(__name__,static_url_path='',static_folder='templates',template_folder='templates')
    app.config.from_object(config[config_name])
    app.jinja_env.auto_reload = True
    app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))

    from wrapcache.database import LruCacheDB
    MemoryAdapter.db = LruCacheDB(size=100)
    config[config_name].init_app(app)

    db.init_app(app)
    #routRgster.init_app(app)
    login_manager.init_app(app)

    if app.config['SSL_REDIRECT']:
        from flask_sslify import SSLify
        sslify = SSLify(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .sys import sys as sys_blueprint
    app.register_blueprint(sys_blueprint,url_prefix='/app/sys')


    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/app/api/v1')


    return app

